package runnables;

import java.util.Vector;

import log.Logger;
import net.rim.blackberry.api.browser.Browser;
import net.rim.device.api.i18n.ResourceBundle;
import net.rim.device.api.system.ApplicationDescriptor;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.Dialog;
import screens.Controller;
import strings.WebcampusResource;
import test.GradeAnalyzer;
import beans.Update;
import exceptions.NoHashException;
import exceptions.NoInstancesException;

public class LoginRunnable implements Runnable, Stoppable, WebcampusResource{

	// RESOURCES
	private static ResourceBundle resources = ResourceBundle.getBundle(BUNDLE_ID, BUNDLE_NAME);

	boolean stop = false;
	Object notifyObject = new Object();
	private Update update=null;

	public void run() {

		GradeAnalyzer ga = GradeAnalyzer.getInstance();

		String user = Controller.getInstance().getUsername();
		String pass = Controller.getInstance().getPassword();

		try{
			//First, check version
			String version = ApplicationDescriptor.currentApplicationDescriptor().getVersion();
			update = ga.getVersion(version);
			if ( stop ) { return; }
			if (update!=null){
				if (update.getIsLatest().equals("true")){
					// nothing to do: continue & login
				} else {
					if (update.getEsObligatoria().equals("true")){
						UiApplication.getUiApplication().invokeAndWait(new Runnable() {
							public void run() {
								int answer = Dialog.ask(Dialog.D_YES_NO, 
										resources.getString(ALERT_MUST_UPDATE));
								if (answer== Dialog.YES){
									Browser.getDefaultSession().displayPage(update.getLinkUltimaVersion());
									System.exit(0);
								} else {
									// can't continue
									System.exit(0);
								}
							}
						});
					} else {
						UiApplication.getUiApplication().invokeAndWait(new Runnable() {
							public void run() {
								//may update
								int answer = Dialog.ask(Dialog.D_YES_NO, 
										resources.getString(ALERT_MAY_UPDATE));
								if (answer==Dialog.YES){
									Browser.getDefaultSession().displayPage(update.getLinkUltimaVersion());
									return;
								} else {
									//nothing to do: continue & login
								}
							}
						});
					}
				}
				// Then, login
				if ( stop ) { return; }
				String hash = ga.getLoginHash(user,pass);
				if (hash.equals("")){
					//wrong username or pass / login error
					throw new NoHashException();
				} else {
					Controller.getInstance().setHash(hash);
				}
				if ( stop ) { return; }
				final Vector instances = ga.getPeriodosClase(hash);
				System.out.println("********************");
				if (instances==null || instances.isEmpty()){
					// instances == null
					throw new NoInstancesException();
				}
				if ( stop ) { return; }
				//if everything is ok, openInstancesScreen(instances);
				UiApplication.getUiApplication().invokeLater(new Runnable() {
					public void run() {
						Controller.getInstance().setLoginMessage("");
						Logger.log("Login ok");
						// etapa 3: uncomment for etapa 3
						new SuscribirPushRunnable(true).run();
						Logger.log("suscribir push runnable is done");
						Controller.getInstance().setInstances(instances);
						Controller.getInstance().openInstancesScreen(instances);
					}
				});
			}
		}
		catch(NoHashException nhe){
			if ( stop ) { return; }
			nhe.printStackTrace();
			Logger.log("No hash exception");
			System.out.println(resources.getString(ALERT_WRONGUSERPASS));
			Controller.getInstance().setLoginMessage(resources.getString(ALERT_WRONGUSERPASS));
		}
		catch (NoInstancesException nie){
			if ( stop ) { return; }
			nie.printStackTrace();
			Logger.log("No instances exception");
			System.out.println(resources.getString(ALERT_NOCOURSESTOSHOW));
			Controller.getInstance().setLoginMessage(resources.getString(ALERT_NOCOURSESTOSHOW));
		}
		catch (Exception e){
			this.stop=true;
			UiApplication.getUiApplication().invokeLater(new Runnable() {
				public void run() {
					System.out.println("ERRORRRRRRRRRR");
					Dialog.inform("Error");
				}
			});
			if ( stop ) { return; }
		}

		//done
		if ( stop ) { return; }
		final Stoppable ourProcessing = this;
		UiApplication.getUiApplication().invokeLater(new Runnable() {
			public void run() {
				if ( ourProcessing.isStopped() ) { 
					return; 
				}
			}
		});
		ga=null;
	}

	public boolean stop() {
		if ( !stop ) {
			stop = true;
			synchronized(notifyObject) {
				notifyObject.notify();
			}
		}
		return true;
	}

	public boolean isStopped() {
		return stop;
	}

}
